package com.ruoyi.know.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.know.domain.UserLikes;
import com.ruoyi.know.service.IPointRecordsService;
import com.ruoyi.know.service.IUserLikesService;
import com.ruoyi.know.service.SensitiveWordService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.know.domain.CommunityPosts;
import com.ruoyi.know.service.ICommunityPostsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 社区帖子Controller
 *
 * @author ruoyi
 * @date 2025-02-10
 */
@RestController
@RequestMapping("/know/posts")
public class CommunityPostsController extends BaseController
{
    @Autowired
    private ICommunityPostsService communityPostsService;
    @Autowired
    private IUserLikesService userLikesService;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Autowired
    private IPointRecordsService pointRecordsService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询社区帖子列表
     */
    @PreAuthorize("@ss.hasPermi('know:posts:list')")
    @GetMapping("/list")
    public TableDataInfo list(CommunityPosts communityPosts)
    {
        startPage();
        List<CommunityPosts> list = communityPostsService.selectCommunityPostsList(communityPosts);
        for (CommunityPosts communityPost : list){
            setCommunityPosts(communityPost);
            setUserInfo(communityPost);
        }
        return getDataTable(list);
    }

    private void setCommunityPosts(CommunityPosts communityPosts){
        //计算点赞数量
        UserLikes userLikes = new UserLikes();
        userLikes.setLikeType(3L);
        userLikes.setInfoId(communityPosts.getPostId());
        communityPosts.setLikeNum(userLikesService.getCountByLikes(userLikes));

        //判断是否已经点过赞
        int countByLikes = userLikesService.getCountByLikes(userLikes);
        communityPosts.setLike(countByLikes>0);
    }

    private void setUserInfo(CommunityPosts communityPosts){
        if (communityPosts.getUserId()!=null){
            communityPosts.setUser(sysUserMapper.selectUserById(communityPosts.getUserId()));
        }
    }

    /**
     * 导出社区帖子列表
     */
    @PreAuthorize("@ss.hasPermi('know:posts:export')")
    @Log(title = "社区帖子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommunityPosts communityPosts)
    {
        List<CommunityPosts> list = communityPostsService.selectCommunityPostsList(communityPosts);
        ExcelUtil<CommunityPosts> util = new ExcelUtil<CommunityPosts>(CommunityPosts.class);
        util.exportExcel(response, list, "社区帖子数据");
    }

    /**
     * 获取社区帖子详细信息
     */
    @PreAuthorize("@ss.hasPermi('know:posts:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable("postId") Long postId)
    {
        CommunityPosts communityPosts = communityPostsService.selectCommunityPostsByPostId(postId);
        setCommunityPosts(communityPosts);
        return success(communityPosts);
    }

    /**
     * 新增社区帖子
     */
    @PreAuthorize("@ss.hasPermi('know:posts:add')")
    @Log(title = "社区帖子", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityPosts communityPosts)
    {
        String postTitle = communityPosts.getPostTitle();
        String postContent = communityPosts.getPostContent();
        // 替换敏感词
//        String cleanTitle = sensitiveWordService.replaceSensitive(postTitle);
//        String cleanContent = sensitiveWordService.replaceWithImgTag(postContent);
//        communityPosts.setPostTitle(cleanTitle);
//        communityPosts.setPostContent(cleanContent);
        //20250402 不替换敏感词
        communityPosts.setPostTitle(postTitle);
        communityPosts.setPostContent(postContent);
        communityPosts.setUserId(getLoginUser().getUserId());
        communityPosts.setCreatedAt(new Date());

        //加积分
        pointRecordsService.earnPoints(getUserId(),"发布帖子",true);
        return toAjax(communityPostsService.insertCommunityPosts(communityPosts));
    }

    /**
     * 修改社区帖子
     */
    @PreAuthorize("@ss.hasPermi('know:posts:edit')")
    @Log(title = "社区帖子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityPosts communityPosts)
    {
        String postTitle = communityPosts.getPostTitle();
        String postContent = communityPosts.getPostContent();
        // 替换敏感词
//        String cleanTitle = sensitiveWordService.replaceSensitive(postTitle);
//        String cleanContent = sensitiveWordService.replaceWithImgTag(postContent);
//        communityPosts.setPostTitle(cleanTitle);
//        communityPosts.setPostContent(cleanContent);
        //20250402 不替换敏感词
        communityPosts.setPostTitle(postTitle);
        communityPosts.setPostContent(postContent);
        communityPosts.setUpdateBy(getUsername());
        communityPosts.setUpdateTime(new Date());
        return toAjax(communityPostsService.updateCommunityPosts(communityPosts));
    }

    /**
     * 删除社区帖子
     */
    @PreAuthorize("@ss.hasPermi('know:posts:remove')")
    @Log(title = "社区帖子", businessType = BusinessType.DELETE)
	@DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds)
    {
        //减积分
        pointRecordsService.earnPoints(getUserId(),"发布帖子",false);
        return toAjax(communityPostsService.deleteCommunityPostsByPostIds(postIds));
    }

    /**
     * 获取前五浏览量的帖子
     * @return
     */
    @GetMapping("/topVisits")
    public AjaxResult getTop5PostsByVisit() {
        return success(communityPostsService.selectTop5PostsByVisit());
    }
}
